<template>
    <el-form ref="banner" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>
        <el-form-item>
            <el-upload class="upload-demo" drag :on-change="chooseImageFn" :on-remove="photoDeleteFn" accept="image/*" :auto-upload="false"
                style="width:100%">
                <div  v-if="imageUrl" style="width: 100%; height: 600px; overflow: hidden;" >
                    <img :src="imageUrl"  style="width: 100%;"/>
                </div>
                <div v-else>
                    <el-icon class="el-icon--upload">
                        <upload-filled />
                    </el-icon>
                    
                    <div class="el-upload__text">
                        <div>拖拽到此处</div>
                        <div>或点击上传</div>
                    </div>
                </div>
                <template #tip>
                    <div class="el-upload__tip"></div>
                </template>
            </el-upload>
        </el-form-item>

        <el-form-item label="轮播图标题" prop="title">
            <el-input v-model="ruleForm.title" />
        </el-form-item>

        <el-form-item label="广告链接" prop="link">
            <el-input v-model="ruleForm.link" />
        </el-form-item>


        <el-form-item label="发布时间" required>
            <el-col :span="11">
                <el-form-item prop="create_time">
                    <el-date-picker v-model="ruleForm.create_time" type="date" label="" placeholder="设置时间"
                        style="width: 100%" />
                </el-form-item>
            </el-col>
            <el-col class="text-center" :span="2">
                <span class="text-gray-500"></span>
            </el-col>
        </el-form-item>

        <!-- 
        <el-form-item label="描述" prop="picUrl">
            <el-input v-model="ruleForm.text" type="textarea" />
        </el-form-item> 
        -->

        <el-form-item>
            <el-button type="primary" @click="addBannerFunc(banner)">发布</el-button>
            <el-button @click="resetForm(banner)">重置</el-button>
        </el-form-item>
    </el-form>
</template>
<script lang="ts" setup>
// 导入格式化时间插件
import moment from "moment";
// 导入消息提示框
import { ElMessage } from 'element-plus';
// 导入定义数据的方法
import { ref, reactive, onMounted } from 'vue';
// 导入表单组件对象
import type { FormInstance, FormRules } from 'element-plus';
// 导入上传文件图标
import { UploadFilled } from '@element-plus/icons-vue';
// 导入相关接口
import { addBanner, photoUpload, photoDelete } from '../../api/request';
import api from '../../api/index'
// 导入创建路由方法
import { useRouter } from 'vue-router';
// 定义路由
const $router = useRouter();
const imageUrl = ref('')
const pic = ref('')

// 定义广告表单实例
const banner = ref<FormInstance>();
// 定义对象记录表单提交的数据
const ruleForm = reactive({
    title: '',
    link: '',
    create_time: '',
    picUrl: '',
})
// 设置表单约束
const rules = reactive<FormRules>({

})
// 编写添加广告方法（轮播图）
const addBannerFunc = async (formObj: FormInstance | undefined) => {
    if (!formObj) return
    await formObj.validate(async (valid, fields) => {
        if (valid) {
            let { title, link, create_time } = ruleForm;
            // let formData = new FormData();
            // formData.append('link', link);
            // formData.append('create_time', moment(new Date(create_time)).format('YYYY-MM-DD HH:mm:ss'))
            // formData.append('picUrl', pic.value);
            // formData.append('title', title);
             // await addBanner(formData)

            await addBanner({ title, link, create_time: moment(new Date(create_time)).format('YYYY-MM-DD HH:mm:ss'), picUrl:  pic.value})
           
                .then(
                    content => {
                        // console.log(content)
                        let { code, msg } = content;
                        // 添加分类名称成功
                        if (code == 200) {
                            ElMessage.success(msg);
                            // 重置表单
                            ruleForm.title = ""
                            ruleForm.link = ""
                            ruleForm.create_time = ""
                            pic.value = "";
                            imageUrl.value = "";
                            // 跳转列表
                            $router.push({path: 'banner_list'})
                        }
                        else {
                            ElMessage.error(msg)
                        }
                    }
                )
                .catch(err=>console.log(err))

        } else {
            console.log('error submit!', fields)
        }
    })
}
// 编写重置广告方法（轮播图）
const resetForm = (formObj: FormInstance | undefined) => {
    if (!formObj) return
    formObj.resetFields()
}

// 选择图标
const chooseImageFn = async (file: any) => {
    if (file) {
        // 创建表单实例
        let fd = new FormData()
        fd.append('photo', file.raw) // 把图片信息传递给服务器 ，服务器存储好图片，再返回一个图片路径
        // 调用上传图片的方法
        await photoUpload(fd)
            .then(
                content => {
                    // console.log("图片路径:", content)
                    let { code, picUrl } = content;
                    if (code == 200) {
                        // 赋值（响应式）
                        imageUrl.value = api.url + picUrl;
                        pic.value = picUrl;
                    }
                    else {
                        ElMessage.error(content.msg);
                    }
                }
            )
    }

}
// 删除图片
const photoDeleteFn = async (picUrl: string) => {
    // console.log("picUrl:",picUrl)
    // console.log(pic.value)
    await photoDelete({ picUrl: pic.value})
        .then(
            content => {
                // console.log(content);
                let { code } = content;
                if (code == 200) {
                    // 重置图片路径
                    imageUrl.value = "";
                }
            }
        )
        .catch(err => console.log(err))
}


</script>
<style lang="scss">
.el-upload-dragger {
    margin-bottom: 20px;
    padding-top: 0px;
    padding-bottom: 0px;

    div {
        padding: 0 !important;
        margin: 0 !important;
    }
}

.demo-ruleForm {
    ::v-deep .el-picker-panel__body {
        z-index: 100000000000;
        background-color: #ccc;
    }
}
</style>